//
//  Button.swift
//  suda
//
//  Created by youai on 2019/7/11.
//  Copyright © 2019年 youi. All rights reserved.
//

import Foundation
import UIKit


class Button : UIButton {
    
    ///设置按钮周围的空间，可支持自动布局
    var extraEdgeInsets : UIEdgeInsets = .zero
    override var intrinsicContentSize: CGSize{
        get{
            let i : CGSize
            let image_ = image(for: .normal)
            if titleLabel != nil{
                titleLabel!.sizeToFit()
                if  image_ == nil{
                    i = titleLabel!.bounds.size
                }else{
                    let tSize = titleLabel!.bounds.size
                    let iSize = image_!.size
                    i = .init(width: tSize.width+iSize.width,
                              height: tSize.height+iSize.height)
                }
            }else{
                if  image_ == nil{
                    i = image_!.size
                }else{
                    i =  super.intrinsicContentSize
                }
            }
            return .init(width: i.width+extraEdgeInsets.left+extraEdgeInsets.right,
                         height: i.height+extraEdgeInsets.top+extraEdgeInsets.bottom)
        }
    }
    
    ///为某个state设置标题和字体颜色
    @discardableResult
    func setTitleAndColor(title:String,color:UIColor,for state:UIControl.State = .normal)->Button{
        setTitle(title, for: state)
        setTitleColor(color, for: state)
        return self
    }
    
    ///在已经设置title的前提下，设置字号和字体样式
    @discardableResult
    func setTitleLabelFont(fontSize:CGFloat,fontWeight:UIFont.Weight = .regular)->Button{
        self.titleLabel?.font = UIFont.systemFont(ofSize: fontSize, weight: fontWeight)
        return self
    }
    
    ///可放大点击区域
    var hitEdgInsets : UIEdgeInsets = .zero
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        let expandedBounds = bounds.inset(by: hitEdgInsets)
        return expandedBounds.contains(point)
    }
    
    ///标题和图片同时左右居中
    func centerTitleAndImage() {
        guard let imageSize = self.imageView?.image?.size else { return }
        self.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: -imageSize.width, bottom: 0, right: 0.0)
        self.titleLabel?.sizeToFit()
        if let size = self.titleLabel?.bounds.size {
            self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0.0, bottom: 0.0, right: -size.width)
            let edgeOffset = (imageSize.width - size.width)*0.25
            self.contentEdgeInsets = UIEdgeInsets(top: 0.0, left: -edgeOffset, bottom: 0.0, right: -edgeOffset)
        }
    }
    
    /// Makes the ``imageView`` appear just to the right of the ``titleLabel``.
    func alignImageRight() {
        if let titleLabel = self.titleLabel, let imageView = self.imageView {
            // Force the label and image to resize.
            titleLabel.sizeToFit()
            imageView.sizeToFit()
//            imageView.contentMode = .bottom
            
            // Set the insets so that the title appears to the left and the image appears to the right.
            // Make the image appear slightly off the top/bottom edges of the button.
            self.titleEdgeInsets = UIEdgeInsets(top: 0, left: -1 * imageView.frame.size.width,
                bottom: 0, right: imageView.frame.size.width)
            self.imageEdgeInsets = UIEdgeInsets(top: 0, left: titleLabel.frame.size.width,
                bottom: 0, right: -1 * titleLabel.frame.size.width)
            
        }
    }
    
    //背景图层（暂定只需要一个图层）
    var customLayer : CALayer? = nil
    //在自动布局完成后，调整背景图层的位置
    override func layoutSubviews() {
        super.layoutSubviews()
        customLayer?.frame = self.bounds
    }
    //插入背景图层
    func insertBackgroundLayer(_ layer:CALayer){
        self.layer.insertSublayer(layer, at: 0)
        self.customLayer = layer
    }
    //绘制渐变背景图层
    @discardableResult
    func drawGradientLayer(
        color1:CGColor,color2:CGColor,
        x1:CGFloat,y1:CGFloat,x2:CGFloat,y2:CGFloat
        )->CAGradientLayer{
        let bgLayer = CAGradientLayer()
        bgLayer.colors = [color1, color2]
        bgLayer.locations = [0, 1]
        bgLayer.startPoint = CGPoint(x: x1, y: y1)
        bgLayer.endPoint = CGPoint(x: x2, y: y2)
        bgLayer.cornerRadius = self.layer.cornerRadius
        self.insertBackgroundLayer(bgLayer)
        return bgLayer
    }

    
    private var _backgroundColor : UIColor? = nil
    
    override var backgroundColor: UIColor? {
        didSet{
            if _backgroundColor == nil {
                _backgroundColor = backgroundColor
            }
        }
    }
    var highLightColor : UIColor? = nil
    override var isHighlighted: Bool {
        didSet{
            if isHighlighted {
                self.backgroundColor = highLightColor ?? _backgroundColor ?? .clear
            }else{
                self.backgroundColor = _backgroundColor ?? .clear
            }
        }
    }
}
